package com.csoa.community.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.UserBean;
import com.csoa.community.services.LocalService;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.ConvertUtils;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.MyImageView;

public class MainActivity extends BaseActivity {

	protected LocalService service;
	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			service = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder ibinder) {
			service = ((LocalService.NoticeBinder) ibinder).getService();
		}
	};
	private TextView unReadCountDocTV;
	private TextView unReadCountEmailTV;
	private TextView loginUsernameTV;

	@Override
	public void initUI() {
		
		setContentView(R.layout.main);
		Log.i("msg", "onStart");
		unReadCountDocTV = (TextView) this.findViewById(R.id.unReadCountTV);
		unReadCountEmailTV = (TextView) this.findViewById(R.id.unReadCountEmaiTV);
		loginUsernameTV = (TextView)this.findViewById(R.id.login_username_main);

		
		//公文
		MyImageView imgAnnouncement_main = (MyImageView) this
				.findViewById(R.id.announcement_main);
		imgAnnouncement_main.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(OfficialDocActivity.class);
			}
		});
		
		
		/**
		 * 设置邮件的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.email_main).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, EmailActivity.class);
				startActivity(intent);
			}
		});
		
		/**
		 * 设置通知公告的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.notice_main).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, TongZhiActivity.class);
				startActivity(intent);
			}
		});
		/**
		 * 设置工作动态的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.dynamic_main).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, GongZuoActivity.class);
				startActivity(intent);
			}
		});
		/**
		 * 设置部门周记的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.daily_main).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, ZhouJiActivity.class);
				startActivity(intent);
			}
		});
		
		
		
			/**
		 * 设置日程的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.chedule_main).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, RiChengActivity.class);
				startActivity(intent);
			}
		});
		
		
		/**
		 * 设置的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.setting_main).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, SettingActivity.class);
				startActivity(intent);
			}
		});
		
		/**
		 * 设置的点击事件
		 * @modify imuto
		 */
		findViewById(R.id.about_main).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, AboutActivity.class);
				startActivity(intent);
			}
		});

	}

	// /**
	// * 登录
	// * @param isTurned登录成功登录失败是否转向
	// */
	// protected void login(boolean isTurned) {
	// this.mIsTurned = isTurned;
	// String strIsAutoLogin = AndroidUtils.getGlobal(GlobalVars.LOGIN,
	// GlobalVars.LOGIN_IS_REMEMBER_PASSWORD, MainActivity.this);
	// if (StringUtils.isEmpty(strIsAutoLogin) || "0".equals(strIsAutoLogin)) {
	// if(isTurned) {
	// startActivity(LoginActivity.class);
	// }
	// } else {
	//
	// String username = AndroidUtils.getGlobal(GlobalVars.LOGIN,
	// GlobalVars.LOGIN_USERNAME, MainActivity.this);
	// String password = AndroidUtils.getGlobal(GlobalVars.LOGIN,
	// GlobalVars.LOGIN_PASSWORD, MainActivity.this);
	// buildRequestLogin(username, password);
	// }
	//
	// }

	public void startActivity(Class<?> activity) {
		Intent intent = new Intent(MainActivity.this, activity);
		startActivityForResult(intent, 0);
	}

	// protected void buildRequestLogin(String aUsername, String aPassword) {
	// showProgress();
	// List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
	// params.add(new BasicNameValuePair("LogName", aUsername));
	// params.add(new BasicNameValuePair("Pwd", aPassword));
	// netRequestLogin(new LoginRequest(params));
	// }
	//
	// private void netRequestLogin(AbstractRequest request) {
	// new WcfAsyncTask(this, new OnUICallback() {
	//
	// @Override
	// public void onGetResult(AbstractRequest request) {
	// dismisProgress();
	// LoginRequest loginRequest = (LoginRequest) request;
	// if (loginRequest.user != null) {
	// loginRequest.user.isLogin = true;
	// GlobalVars.currentUser = loginRequest.user;
	// if(mIsTurned) {
	// startActivity(OfficialDocActivity.class);
	// }else {
	// startService();
	// }
	// }
	// }
	//
	// @Override
	// public void onCancel() {
	// dismisProgress();
	// if(mIsTurned) {
	// startActivity(LoginActivity.class);
	// }else {
	// startService();
	// }
	//
	// }
	//
	// @Override
	// public void onProgress(int progress, String msg) {
	// dismisProgress();
	// MainActivity.this.showToast(msg);
	// }
	// }).execute(request);
	// }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(myBroadcastReceiver);
		this.unbindService(connection);
		if (service != null) {
			service = null;
		}
		Log.i("msg", "onDestroy");
		// 将当前用户状态置空
//		GlobalVars.currentUser = null;

	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.i("msg", "onPause");
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if(GlobalVars.currentUser == null || StringUtils.isEmpty(GlobalVars.currentUser.loginName)) {
			String strUsername = AndroidUtils.getGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_USERNAME, this);
			
			String strReallyUsername = AndroidUtils.getGlobal(GlobalVars.LOGIN, GlobalVars.LOGIN_REALLY_USERNAME,
					 this);
			
			UserBean user = new UserBean();
			user.loginName = strUsername;
			user.userName = strReallyUsername;
			GlobalVars.currentUser = user;
			
		}
		loginUsernameTV.setText("您好 " + GlobalVars.currentUser.userName + "  ,  " + ConvertUtils.getCurrentTime());
		Log.i("msg", "onResume");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		
		Log.i("msg", "onRestart");
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i("msg", "onStart");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i("msg", "onStop");
	}

	private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();

	class MyBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String document = intent.getStringExtra("document");
			String email = intent.getStringExtra("email");
			
			//未读公文数
			showUnReadCount(intent,document,"document",unReadCountDocTV);
			
			//未读邮件数
			showUnReadCount(intent,email,"email",unReadCountEmailTV);
			
			
//			if(!StringUtils.isEmpty(email) && document.equals("email")) {
//				String unReadCount = intent.getStringExtra("unReadCount");
//				unReadCountEmailTV.setText(unReadCount);
//				unReadCountEmailTV.setVisibility(View.VISIBLE);
//			} else {
//				unReadCountEmailTV.setVisibility(View.GONE);
//			}
			
			
			

		}
	}
	
	/**
	 * 显示未读数
	 * @param type 未读类型
	 * @param unReadCountTVType未读类型TextView
	 */
	public void showUnReadCount(Intent intent, String type, String typeValue, TextView unReadCountTVType) {
		if (!StringUtils.isEmpty(type) && type.equals(typeValue)) {
			String unReadCount = intent.getStringExtra("unReadCount");
//			if(!unReadCount.equals("0")) {
				unReadCountTVType.setText(unReadCount);
				unReadCountTVType.setVisibility(View.VISIBLE);
//			}else {
//				unReadCountTVType.setVisibility(View.GONE);
//			}
		} 
	}

	private static Boolean isExit = false;
	private static Boolean hasTask = false;
	Timer tExit = new Timer();
	TimerTask task = new TimerTask() {

		@Override
		public void run() {
			isExit = false;
			hasTask = true;
		}
	};
	private boolean mBinding = false;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isExit == false) {
				isExit = true;
				this.showToast("再按一次退出程序");
				if (!hasTask) {
					tExit.schedule(task, 2000);
				}
			} else {
				finish();
				System.exit(1);
			}
		}
		return false;
	}

	

	private void startService() {
		if (mBinding) {
			this.unbindService(connection);
		}
		Intent intent = new Intent();
		intent.setClass(this, LocalService.class);
		this.bindService(intent, connection, BIND_AUTO_CREATE);
		mBinding = true;
	}

	@Override
	public void initData() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(GlobalVars.ACTION_BROADCASTRECEIVEE);
		this.registerReceiver(myBroadcastReceiver, filter);
		startService();
		// login(false);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		startService();
	}
}
